package br.com.bacabeleireiros.util.controller;

import java.io.Serializable;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BaseBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private ResourceBundle bundle;
	
	public FacesContext getFacesContext() {
		return FacesContext.getCurrentInstance();
	}	
	
	public Logger getLogger() {
		return this.logger;
	}
	
	public RequestContext getPaginaAtual() {
		return RequestContext.getCurrentInstance();
	}
	
	protected void addErrorMessage(String componetId, String errorMessage) {
		addMessage(componetId, errorMessage, FacesMessage.SEVERITY_ERROR);
	}
	
	protected void addErrorMessage(String errorMessage) {
		addErrorMessage(null, errorMessage);
	}
	
	protected void addInfoMessage(String componetId, String infoMessage) {
		addMessage(componetId, infoMessage, FacesMessage.SEVERITY_INFO);
	}
	
	protected void addInfoMessage(String infoMessage) {
		addInfoMessage(null, infoMessage);
	}
	
	protected void addWarnMessage(String componetId, String infoMessage) {
		addMessage(componetId, infoMessage, FacesMessage.SEVERITY_WARN);
	}
	
	protected void addWarnMessage(String infoMessage) {
		addWarnMessage(null, infoMessage);
	}	
	
	private void addMessage(String componentId, String msg, Severity severity) {
		FacesMessage message = new FacesMessage(msg);
		message.setSeverity(severity);
		FacesContext.getCurrentInstance().addMessage(componentId, message);
		FacesContext.getCurrentInstance().getMessages();
	
	}

	public ResourceBundle getBundle() {
		if (bundle == null) {
			FacesContext context = FacesContext.getCurrentInstance();
			bundle = context.getApplication().getResourceBundle(context, "msg");
		}
		return bundle;
	}

	public String getValue(String key) {

		String result = null;
		try {
			result = getBundle().getString(key);
		} catch (MissingResourceException e) {
			result = "???" + key + "??? not found";
		}
		return result;
	}
	
	public HttpServletRequest getRequest() {
		return (HttpServletRequest) getFacesContext().getExternalContext().getRequest();
	}
	
	public HttpSession getSession() {
		return getRequest().getSession();		
	}	
	
}


